package cn.itcast.template;

import cn.itcast.properties.SmsProperties;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;

/**
 * Demo class
 *
 * @author gyc
 * @date 2021 /9/27
 */
public class SmsTemplate {
    private SmsProperties smsProperties;

    /**
     * Instantiates a new Sms template.
     *
     * @param smsProperties the sms properties
     */
    public SmsTemplate(SmsProperties smsProperties) {
        this.smsProperties = smsProperties;
    }


    /**
     * Send sms.
     *
     * @param mobile the mobile
     * @param code   the code
     */
    public void SendSms(String mobile, String code){
        try {
            Config config = new Config()
                    // 您的AccessKey ID
                    .setAccessKeyId(smsProperties.getAccessKey())
                    // 您的AccessKey Secret
                    .setAccessKeySecret(smsProperties.getSecret());

            // 访问的域名
            config.endpoint = "dysmsapi.aliyuncs.com";
            Client client = new Client(config);
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(mobile)
                    .setSignName(smsProperties.getSignName())
                    .setTemplateCode(smsProperties.getTemplateCode())
                    .setTemplateParam("{\"code\":\""+code+"\"}");
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            if ("OK".equals(sendSmsResponse.getBody().getCode())) {
                System.out.println("验证码发送成功");
            }
            System.out.println(sendSmsResponse.getBody().getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
